import subjectApi from '@/api/subject'
import chapterApi from '@/api/chapter'

/* eslint-disable */
//全局状态 == 全局数据
//...mapState('exam', { subjects: state => state.subjects })：将全局的state映射为计算属性
/* eslint-disable */
const state = {
  subjects: [],
  chapters: []
}

const getters = {
  subjectEnumFormat: (state) => (key) => { // getters用于对Store中数据进行加工形成新的数据（类似计算属性，store变化则变化）不会修改store的数据
    for (let item of state.subjects) {
      if (item.id === key) {
        return item.name + ' ( ' + item.levelName + ' )'
      }
    }
    return null
  },
  chapterEnumFormat: (state) => (key) => {
    for ( let item of state.chapters) {
      if (item.id === key) {
        return item.name
      }
    }
    return null
  }
}

/* eslint-disable */
//如果通过异步操作变更数据，必须通过action，而不能使用mutation，但是在action中还是要通过触发Mutation的方式间接变更数据
//在actions中，不能直接修改state中的数据，必须通过context.commit()触发某个mutation
//在this.&store.dispatch("initSubject"):触发某个action
//...mapActions('exam', { initSubject: 'initSubject' }):mapActions将全局的actions函数，映射为methods中的方法
/* eslint-disable */
const actions = {
  initSubject ({ commit }, action) {
    subjectApi.list().then(re => {
      commit('setSubjects', re.response)
      if (action !== undefined) {
        action()
      }
    })
  },
  initChapter ({commit}, action) {
    chapterApi.list().then(re => {
      commit('setChapters', re.response)
      if(action != undefined){
        action()
      }
    })
  }
}

/* eslint-disable */
//mutation：变更操作 == 各种函数
//mapMutation可以将mutation中方法映射为methods中的方法
/* eslint-disable */
const mutations = {
  setSubjects: (state, subjects) => {
    state.subjects = subjects
  },
  setChapters: (state, chapters) => {
    state.chapters = chapters
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
